package cn.bdqn.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

@WebServlet("/doUpload")
public class DoUploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String fileName="";
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        PrintWriter out=response.getWriter();

        //定义要上传的路径
        String path=request.getSession().getServletContext().getRealPath("upload/");
        //获取当前请求是否是multipart即二进制请求方式
        boolean isMultipart= ServletFileUpload.isMultipartContent(request);
        if(isMultipart){
            DiskFileItemFactory diskFileItemFactory=new DiskFileItemFactory();
            ServletFileUpload servletFileUpload=new ServletFileUpload(diskFileItemFactory);
            //开始解析请求中的数据
            try {
                List<FileItem> fileItemList=servletFileUpload.parseRequest(request);
                Iterator<FileItem> itemIterator=fileItemList.iterator();
                while(itemIterator.hasNext()){
                    //从迭代器获取文件对象
                    FileItem fileItem=itemIterator.next();
                    if(!fileItem.isFormField()){//判断是一个文件对象
                        //获取文件的名字
                        fileName=fileItem.getName();
                        File file=new File(fileName);
                        File saveFile=new File(path,file.getName());
                        fileItem.write(saveFile);
                        out.print("<h1>上传的文件名是："+file.getName()
                                +"，文件大小是："+fileItem.getSize()+"</h1>");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
